package api

import (
	"net"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/pkg/errors"

	"gitee.com/sillyman/PingHostsWebView/models"
	"gitee.com/sillyman/PingHostsWebView/modules/db"
)

// CountPingRecords 返回记录的数量
func CountPingRecords(c echo.Context) error {
	ip := net.ParseIP(c.Param("ip"))
	if ip == nil {
		return newHttpErrBadParam(errors.New("This is not a valid textual representation of an IP address"))
	}

	// 对应的前端格式是：new Date().toISOString()
	timeLayout := "2006-01-02T15:04:05.000Z"

	fromTime, err := time.Parse(timeLayout, c.QueryParam("fromTime"))
	if err != nil {
		return newHttpErrBadParam(err)
	}
	toTime, err := time.Parse(timeLayout, c.QueryParam("toTime"))
	if err != nil {
		return newHttpErrBadParam(err)
	}
	fromTime, toTime = fromTime.Local(), toTime.Local()

	mydb := db.MustOpenPingRecordDB(ip)
	defer func() {
		sqlDB, _ := mydb.DB()
		_ = sqlDB.Close()
	}()

	var count int64
	if err := mydb.Model(&models.PingRecord{}).Where("created_at BETWEEN ? AND ?", fromTime, toTime).Count(&count).Error; err != nil {
		return newHttpErrReadDB(err)
	}

	return respJSON200(c, count)
}

// GetPingRecords 列出记录
func GetPingRecords(c echo.Context) error {
	ip := net.ParseIP(c.Param("ip"))
	if ip == nil {
		return newHttpErrBadParam(errors.New("This is not a valid textual representation of an IP address"))
	}

	// 对应的前端格式是：new Date().toISOString()
	timeLayout := "2006-01-02T15:04:05.000Z"

	fromTime, err := time.Parse(timeLayout, c.QueryParam("fromTime"))
	if err != nil {
		return newHttpErrBadParam(err)
	}
	toTime, err := time.Parse(timeLayout, c.QueryParam("toTime"))
	if err != nil {
		return newHttpErrBadParam(err)
	}
	fromTime, toTime = fromTime.Local(), toTime.Local()

	mydb := db.MustOpenPingRecordDB(ip)
	defer func() {
		sqlDB, _ := mydb.DB()
		_ = sqlDB.Close()
	}()

	records := make([]models.PingRecord, 0, 10000)
	if err := mydb.Model(&models.PingRecord{}).Where("created_at BETWEEN ? AND ?", fromTime, toTime).Find(&records).Error; err != nil {
		return newHttpErrReadDB(err)
	}

	return respJSON200(c, records)
}
